from CvPythonExtensions import *
from WriterUtils import *

import CvScreenEnums
import CvUtil
import CvConfigParser
import CvPath
import os
import os.path
import Popup as PyPopup
import shutil 

# globals
gc = CyGlobalContext()
ArtFileMgr = CyArtFileMgr()
localText = CyTranslator()

# Change this to change the location where the resulting CIV4CivilizationInfos.xml file 
# will be saved. So if the default value is left to "Test" then the 
# CIV4CivilizationInfos.xml file would be written in a directory called "Test" inside 
# of the Tech Tree Editor mod folder.
# Default value is Test
g_strSaveDirectoryLocation = "Test"

# Change the value to false if the assets directory structure shouldn't be 
# created at the directory specified by the "Save Directory Location".
# Default value is True
g_bCreateAssetHierarchy = True

# Change the value to false if the changes made shouldn't be saved into the 
# assets directory for the tech editor. Changing it to false will require 
# manual copying of the saved files from the directory specified in the 
# "Save Directory Location" configurable option to the editor's asset directory 
# when wanting to edit existing mod files.
# Default value is True
g_bSaveChangesInEditorAssetsDirectory = True

def loadConfigurationValues():
	global g_strSaveDirectoryLocation
	global g_bCreateAssetHierarchy
	global g_bSaveChangesInEditorAssetsDirectory
	
	config = CvConfigParser.CvConfigParser("ViSa_v3.ini")

	if(config != None):
		g_strSaveDirectoryLocation = config.get("Tech Tree Editor", "Save Directory Location", "Test")
		g_bCreateAssetHierarchy = config.getboolean("Tech Tree Editor", "Create Asset Hierarchy", True)
		g_bSaveChangesInEditorAssetsDirectory = config.getboolean("Tech Tree Editor", "Save Changes In Editor Assets Directory", True)

		if(len(g_strSaveDirectoryLocation) == 0):
			g_strSaveDirectoryLocation = "Test"
			
class CivilizationInfoWriter:
		
	def __init__(self):
		loadConfigurationValues()
		
	def nonDefaultBuildingsDefined(self, iCivilization):

		objCivilizationInfo = gc.getCivilizationInfo(iCivilization)

		for iI in range(gc.getNumBuildingClassInfos()):
			if(objCivilizationInfo.getCivilizationBuildings(iI) != gc.getBuildingClassInfo(iI).getDefaultBuildingIndex()):
				return true
		
		return false
		
	def nonDefaultUnitsDefined(self, iCivilization):

		objCivilizationInfo = gc.getCivilizationInfo(iCivilization)

		for iI in range(gc.getNumUnitClassInfos()):
			if(objCivilizationInfo.getCivilizationUnits(iI) != gc.getUnitClassInfo(iI).getDefaultUnitIndex()):
				return true
		
		return false		
		
	def freeUnitClassesDefined(self, iCivilization):

		objCivilizationInfo = gc.getCivilizationInfo(iCivilization)

		for iI in range(gc.getNumUnitClassInfos()):
			if(objCivilizationInfo.getCivilizationFreeUnitsClass(iI) > 0):
				return true

		return false	
		
	def freeBuildingClassesDefined(self, iCivilization):

		objCivilizationInfo = gc.getCivilizationInfo(iCivilization)

		for iI in range(gc.getNumBuildingClassInfos()):
			if(objCivilizationInfo.isCivilizationFreeBuildingClass(iI)):
				return true

		return false	
		
	def freeTechsDefined(self, iCivilization):

		objCivilizationInfo = gc.getCivilizationInfo(iCivilization)

		for iI in range(gc.getNumTechInfos()):
			if(objCivilizationInfo.isCivilizationFreeTechs(iI)):
				return true

		return false
		
	def disableTechsDefined(self, iCivilization):

		objCivilizationInfo = gc.getCivilizationInfo(iCivilization)

		for iI in range(gc.getNumTechInfos()):
			if(objCivilizationInfo.isCivilizationDisableTechs(iI)):
				return true

		return false
	
	def isLeadersDefined(self, iCivilization):
		
		objCivilizationInfo = gc.getCivilizationInfo(iCivilization)

		for iI in range(gc.getNumLeaderHeadInfos()):
			if(objCivilizationInfo.isLeaders(iI)):
				return true
		return false
		
	def printCivilization(self, iCivilization):
		
		objCivilizationInfo = gc.getCivilizationInfo(iCivilization)

		szText = ""
		
		szText = appendString(szText,"		<CivilizationInfo>")
		
		szText = appendString(szText,"			<Type>%s</Type>" %(objCivilizationInfo.getType()))
		szText = appendString(szText,"			<Description>%s</Description>" %(objCivilizationInfo.getTextKey()))
		szText = appendString(szText,"			<ShortDescription>%s</ShortDescription>" %(objCivilizationInfo.getShortDescriptionKey()))
		szText = appendString(szText,"			<Adjective>%s</Adjective>" %(objCivilizationInfo.getAdjectiveKey()))
		szText = appendString(szText,"			<Civilopedia>%s</Civilopedia>" %(objCivilizationInfo.getCivilopediaKey()))
		szText = appendString(szText,"			<DefaultPlayerColor>%s</DefaultPlayerColor>" %(gc.getPlayerColorInfo(objCivilizationInfo.getDefaultPlayerColor()).getType()))

		szText = appendString(szText,"			<ArtDefineTag>%s</ArtDefineTag>" %(objCivilizationInfo.getArtDefineTag()))
			
		szText = appendString(szText,"			<ArtStyleType>%s</ArtStyleType>" %(gc.getArtStyleTypes(objCivilizationInfo.getArtStyleType())))

		szText = appendString(szText,"			<bPlayable>%s</bPlayable>" %(boolToInt(objCivilizationInfo.isPlayable())))
		szText = appendString(szText,"			<bAIPlayable>%s</bAIPlayable>" %(boolToInt(objCivilizationInfo.isAIPlayable())))

		szText = appendString(szText,"			<Cities>")
		for iCity in range(objCivilizationInfo.getNumCityNames()):
			szText = appendString(szText,"				<City>%s</City>" %(objCivilizationInfo.getCityNames(iCity)))
			
		szText = appendString(szText,"			</Cities>")

		if(self.nonDefaultBuildingsDefined(iCivilization)):
			szText = appendString(szText,"			<Buildings>")
			for iI in range(gc.getNumBuildingClassInfos()):
				if(objCivilizationInfo.getCivilizationBuildings(iI) != gc.getBuildingClassInfo(iI).getDefaultBuildingIndex()):
					szText = appendString(szText,"				<Building>")
					szText = appendString(szText,"					<BuildingClassType>%s</BuildingClassType>" %(gc.getBuildingClassInfo(iI).getType()))
					if(objCivilizationInfo.getCivilizationBuildings(iI) > -1):
						szText = appendString(szText,"					<BuildingType>%s</BuildingType>" %(gc.getBuildingInfo(objCivilizationInfo.getCivilizationBuildings(iI)).getType()))
					else:
						szText = appendString(szText,"					<BuildingType>NONE</BuildingType>" %())
					szText = appendString(szText,"				</Building>")
								
			szText = appendString(szText,"			</Buildings>")
		else:
			szText = appendString(szText,"			<Buildings/>")
		
		if(self.nonDefaultUnitsDefined(iCivilization)):
			szText = appendString(szText,"			<Units>")
			for iI in range(gc.getNumUnitClassInfos()):
				if(objCivilizationInfo.getCivilizationUnits(iI) != gc.getUnitClassInfo(iI).getDefaultUnitIndex()):
					szText = appendString(szText,"				<Unit>")
					szText = appendString(szText,"					<UnitClassType>%s</UnitClassType>" %(gc.getUnitClassInfo(iI).getType()))
					if(objCivilizationInfo.getCivilizationUnits(iI) > -1):
						szText = appendString(szText,"					<UnitType>%s</UnitType>" %(gc.getUnitInfo(objCivilizationInfo.getCivilizationUnits(iI)).getType()))
					else:
						szText = appendString(szText,"					<UnitType>NONE</UnitType>" %())
					szText = appendString(szText,"				</Unit>")
								
			szText = appendString(szText,"			</Units>")
		else:
			szText = appendString(szText,"			<Units/>")
		
		if(self.freeUnitClassesDefined(iCivilization)):
			szText = appendString(szText,"			<FreeUnitClasses>")
			for iI in range(gc.getNumUnitClassInfos()):
				if(objCivilizationInfo.getCivilizationFreeUnitsClass(iI) > 0):
					szText = appendString(szText,"				<FreeUnitClass>")
					szText = appendString(szText,"					<UnitClassType>%s</UnitClassType>" %(gc.getUnitClassInfo(iI).getType()))
					szText = appendString(szText,"					<iFreeUnits>%s</iFreeUnits>" %(objCivilizationInfo.getCivilizationFreeUnitsClass(iI)))
					szText = appendString(szText,"				</FreeUnitClass>")
								
			szText = appendString(szText,"			</FreeUnitClasses>")
		else:
			szText = appendString(szText,"			<FreeUnitClasses/>")
		
		if(self.freeBuildingClassesDefined(iCivilization)):
			szText = appendString(szText,"			<FreeBuildingClasses>")
			for iI in range(gc.getNumBuildingClassInfos()):
				if(objCivilizationInfo.isCivilizationFreeBuildingClass(iI)):
					szText = appendString(szText,"				<FreeBuildingClass>")
					szText = appendString(szText,"					<BuildingClassType>%s</BuildingClassType>" %(gc.getBuildingClassInfo(iI).getType()))
					szText = appendString(szText,"					<bFreeBuildingClass>1</bFreeBuildingClass>")
					szText = appendString(szText,"				</FreeBuildingClass>")
								
			szText = appendString(szText,"			</FreeBuildingClasses>")
		else:
			szText = appendString(szText,"			<FreeBuildingClasses/>")
		
		if(self.freeTechsDefined(iCivilization)):
			szText = appendString(szText,"			<FreeTechs>")
			for iI in range(gc.getNumTechInfos()):
				if(objCivilizationInfo.isCivilizationFreeTechs(iI)):
					szText = appendString(szText,"				<FreeTech>")
					szText = appendString(szText,"					<TechType>%s</TechType>" %(gc.getTechInfo(iI).getType()))
					szText = appendString(szText,"					<bFreeTech>1</bFreeTech>")
					szText = appendString(szText,"				</FreeTech>")
								
			szText = appendString(szText,"			</FreeTechs>")
		else:
			szText = appendString(szText,"			<FreeTechs/>")
		
		if(self.disableTechsDefined(iCivilization)):
			szText = appendString(szText,"			<DisableTechs>")
			for iI in range(gc.getNumTechInfos()):
				if(objCivilizationInfo.isCivilizationDisableTechs(iI)):
					szText = appendString(szText,"				<DisableTech>")
					szText = appendString(szText,"					<TechType>%s</TechType>" %(gc.getTechInfo(iI).getType()))
					szText = appendString(szText,"					<bDisableTech>1</bDisableTech>")
					szText = appendString(szText,"				</DisableTech>")
								
			szText = appendString(szText,"			</DisableTechs>")
		else:
			szText = appendString(szText,"			<DisableTechs/>")

		szText = appendString(szText,"			<InitialCivics>")
		for iI in range(gc.getNumCivicOptionInfos()):
			szText = appendString(szText,"				<CivicType>%s</CivicType>" %(gc.getCivicInfo(objCivilizationInfo.getCivilizationInitialCivics(iI)).getType()))
		szText = appendString(szText,"			</InitialCivics>")
					
					
		if(self.isLeadersDefined(iCivilization)):
			szText = appendString(szText,"			<Leaders>")
				
			for iI in range(gc.getNumLeaderHeadInfos()):
				if(objCivilizationInfo.isLeaders(iI)):
					szText = appendString(szText,"				<Leader>")

					szText = appendString(szText,"					<LeaderName>%s</LeaderName>" %(gc.getLeaderHeadInfo(iI).getType()))
					szText = appendString(szText,"					<bLeaderAvailability>1</bLeaderAvailability>")				
					szText = appendString(szText,"				</Leader>")
			szText = appendString(szText,"			</Leaders>")
		else:
			szText = appendString(szText,"			<Leaders/>")

		if(len(objCivilizationInfo.getSelectionSoundScriptTag()) > 0):
			szText = appendString(szText,"			<CivilizationSelectionSound>%s</CivilizationSelectionSound>" %(objCivilizationInfo.getSelectionSoundScriptTag()))
		else:
			szText = appendString(szText,"			<CivilizationSelectionSound/>")

		if(len(objCivilizationInfo.getActionSoundScriptTag()) > 0):
			szText = appendString(szText,"			<CivilizationActionSound>%s</CivilizationActionSound>" %(objCivilizationInfo.getActionSoundScriptTag()))
		else:
			szText = appendString(szText,"			<CivilizationActionSound/>")
				
		szText = appendString(szText,"		</CivilizationInfo>")
			
		return szText

						
	def printCivilizations(self):	
	
		strSavePath = ""
		strFileSavePath = ""
		strModPath = ""
		strModAssetPath = ""
		strModAssetSavePath = ""
		strModAssetPath = ""
		
		if(os.access(CvPath.userActiveModDir,os.F_OK)):
			strModPath = CvPath.userActiveModDir
		elif(os.access(CvPath.installActiveModDir,os.F_OK)):
			strModPath = CvPath.installActiveModDir
		else:
			self.dataSavePopup(false)
			return
			
		strSavePath = "%s\%s" %(strModPath,g_strSaveDirectoryLocation)
		strModAssetPath = "%s\\Assets\\" %(strModPath)
		
		if(g_bCreateAssetHierarchy):
			strSavePath += "\Assets\XML\Civilizations" 

		strFileSavePath = "%s\%s" %(strSavePath, "CIV4CivilizationInfos.xml")

		try:
			if(os.access(strSavePath,os.F_OK)):
				if(os.access(strFileSavePath,os.F_OK)):
					os.remove(strFileSavePath)
				os.removedirs(strSavePath)
		except:
			pass
			
		if(not os.access(strSavePath,os.F_OK)):
			os.makedirs(strSavePath)

							
		szText = "<?xml version=\"1.0\"?>"
		szText = appendString(szText,"<!-- Created by Tech Civilizeditor %s by TheLopez-->" %(editorVersion()))
		szText = appendString(szText,"<!-- Sid Meier's Civilization 4 -->")
		szText = appendString(szText,"<!-- Copyright Firaxis Games 2005 -->")
		szText = appendString(szText,"<!-- -->")
		szText = appendString(szText,"<!-- Civilization Infos -->")
		szText = appendString(szText,"<Civ4CivilizationInfos xmlns=\"x-schema:CIV4CivilizationsSchema.xml\">")
		szText = appendString(szText,"	<CivilizationInfos>")
				
		for iCivilization in range(gc.getNumCivilizationInfos()):

			if(gc.getCivilizationInfo(iCivilization).isDeleted()):
				continue

			szText = appendString(szText,self.printCivilization(iCivilization))
			
						
		szText = appendString(szText,"	</CivilizationInfos>")
		szText = appendString(szText,"</Civ4CivilizationInfos>")

			
		fd = os.open(strFileSavePath, os.O_CREAT)
		os.close(fd)

		fd = os.open(strFileSavePath, os.O_RDWR)
		os.write(fd, szText)
		os.close(fd)
		
		if(g_bSaveChangesInEditorAssetsDirectory):
			strModAssetPath = "%s\%s" %(strModPath,"\Assets\XML\Civilizations")
			strModAssetSavePath = "%s\%s" %(strModPath, "\Assets\XML\Civilizations\CIV4CivilizationInfos.xml")
			try:
				if(os.access(strModAssetPath,os.F_OK)):
					if(os.access(strModAssetSavePath,os.F_OK)):
						os.remove(strModAssetSavePath)
			except:
				pass
			
			if(not os.access(strModAssetPath,os.F_OK)):
				os.makedirs(strModAssetPath)

			fd = os.open(strModAssetSavePath, os.O_CREAT)
			os.close(fd)

			fd = os.open(strModAssetSavePath, os.O_RDWR)
			os.write(fd, szText)
			os.close(fd)
	

